let timeLock = 0
let djLock = 0
function AllReady() {
    let Flag = false;
    let mstform = Ext.getCmp("MatPM"); //获取容器
    let dgrid = Ext.getCmp("MatPD");
    let dstore = dgrid?.store;
    let toolbar = Ext.getCmp("toolbar");
    try {
        toolbar.get("imp").setText("引用设备清单明细");
        toolbar.get("imp_push").setText("下推采购合同/定价申请");
        {
            mstform.getItem("UserTitle").userSetMustInput(false);
            mstform.getItem("UserTitle").setVisible(false); //true-可见   false-x隐藏
            mstform.getItem("UserTitle").setValue("采购申请")
        }
    } catch (error) {
        console.log("推送按钮不存在 或者正在下推别的单子");
        mstform.getItem("UserTitle").setValue("采购申请")

    }

    // //主表通用帮助过滤
    // mstform
    //     .getItem("user_tqsgdh")
    //     .on("beforetriggerclick", function (eOp, ignoreBeforeEvent) {
    //         let sjh = mstform.getItem("user_sjh").getValue();
    //         if (Ext.isEmpty(sjh)) {
    //             Ext.Msg.alert("提示", "未选择项目,没检测到商机号");
    //             mstform.getItem("PhidPc").focus();
    //             return false;
    //         } else {
    //             mstform.getItem("user_tqsgdh").setOutFilter({
    //                 u_opportunity_no: sjh, //phid_pc 字段是通用帮助中的字段
    //             });
    //         }
    //     });
    mstform.on("dataready", async function () {
        console.log(`加载一次`);
        execServer(
            "projectSjbm",
            { phid: `${mstform.getItem("PhidPc").getValue()}` },
            function (res) {
                try {
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    //商机号
                    mstform.getItem("user_sjh").setValue(datas.user_sjbm);
                    //商机编码
                    mstform.getItem("user_sjname").setValue(datas.user_sjmc);
                    BatchBindCombox([mstform.getItem("user_sjh")]);
                    BatchBindCombox([mstform.getItem("user_sjname")]);
                } catch (error) { }
            }
        );
        if (otype == "add") {
            mstform.getItem("user_pro_type").setValue("01");
            getPtInfoByPhid();
            //新增逻辑
            execServer("GETuserdept", { phid: $appinfo.userID }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                if (res.count > 0) {
                    mstform.getItem("user_apply_dept").setValue(datas.dept_id); //申请部门
                    mstform.getItem("user_apply_person").setValue($appinfo.userID); //申请人
                    BatchBindCombox([mstform.getItem("user_apply_dept")]);
                    BatchBindCombox([mstform.getItem("user_apply_person")]);
                }
            });

            if ($appinfo.ocode) {
                execServer("GETORG", { code: $appinfo.ocode }, function (res) {
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    if (res.count > 0) {
                        mstform.getItem("user_org_apply").setValue(datas.phid);
                        BatchBindCombox([mstform.getItem("user_org_apply")]);
                    }
                });
            }
        }
        if (!toolbar.get("imp")) {
            /**
             *@author 崔赛豪
             * @description 保存数据处理数据 多层封装方便以后扩展其他功能 保证容错率 不要动
             * @param {string} k key
             * @param {any} v value
             * @param {any} t type
             */
            function saveData(k, v) {
                localStorage.setItem(k, JSON.stringify(v));
            }

            function getData(k) {
                const storedValue = localStorage.getItem(k);
                if (storedValue) {
                    return JSON.parse(storedValue);
                }
                return null;
            }
            function clearData(k) {
                localStorage.removeItem(k);
            }
            function AsyncTypeData(k, t, v) {
                switch (t) {
                    case "save":
                        saveData(k, v);
                        break;
                    case "get":
                        getData(k);
                        console.log(getData(k), "getData(k)");
                        break;
                    case "clear":
                        clearData(k);
                        break;
                    default:
                        console.log("Invalid t");
                }
            }
            AsyncTypeData("ArrData", "get");
            
            // async function fun() {
            //     timeLock = setTimeout(() => {
            //         if (!Flag) {
            //             clearTimeout(timeLock)
            //             fun();
            //         }
            //         Ext.getCmp("MatPD").store.each(function (item, index) {
            //             getData("ArrData").forEach((i, v) => {
            //                try{
            //                 if (
            //                     !i.checked &&
            //                     item.raw.user_sbqd_no == i.u_equipment_list_no
            //                 ) {
            //                     Ext.getCmp("MatPD").store.remove(item);
            //                 }
            //                } catch(e){

            //                }
            //                 Flag = true;
            //             });
            //         });
            //     }, 300);
            // }
            // await fun();
        }
    });
    dgrid.getColumn("user_rest_wz").addListener("click", function () {
        let data = dgrid.getSelectionModel().getSelection();
        console.log("进入加载元素");
        console.log(data[0].data, "data");
        if (!data[0].data.PhidItemData) return;
        execServer(
            "getrestqtyview",
            { itemName: `'${data[0].data.PhidItemData}'` },
            function (res) {
                if (res.data.length > 0) {
                    console.log(JSON.parse(res.data)[0].extendObjects, "有数据");
                    let mergedData = mergeSimilarItems2(JSON.parse(res.data));
                    createTable(mergedData);
                    if (mergedData[0].extendObjects.u_rest_qty) {
                        dgrid.getView().refresh();
                    }
                } else {
                    console.log(res, "未查到数据");
                    dgrid.getView().refresh();
                }

                dgrid.getView().refresh();
            }
        );
    });
    mstform.getItem("PhidPc").addListener("helpselected", function (args) {
        getPtInfoByPhid();
    });

    mstform.getItem("user_sjh").addListener("change", async function (args) {
        console.log(args, "sjh11111xxx???111");
        console.log(mstform.getValues().user_sjh, "mstform.getValues().user_sjh");
        if (!mstform.getValues().user_sjh) return;

        console.log("进入加载元素", "user_sjh", mstform.getValues().user_sjh);

        await execServer(
            "getSearchgcdhInfo",
            { sjh: `'${mstform.getValues().user_sjh}'` },
            function (res) {
                console.log("66666666666666666666666666666");
                if (!res.data.length > 0) return;
                console.log("res", JSON.parse(res.data));
                const {
                    bill_no = "",
                    u_ad_limit = "",
                    u_ad_total_amt = "",
                    bill_dt = "",
                } = JSON.parse(res.data)[0].extendObjects;
                let data = dgrid.getSelectionModel().getSelection();
                console.log(
                    bill_no,
                    u_ad_limit,
                    u_ad_total_amt - u_ad_limit,
                    "u_ad_total_amt - u_ad_limit"
                );
                // mstform.getItem("user_tqsgdh").setValue(bill_no);
                BatchBindCombox([mstform.getItem("user_tqsgdh")]);
                mstform.getItem("user_tqsg_amt").setValue(u_ad_limit);
                mstform
                    .getItem("user_rest_sgamt")
                    .setValue(u_ad_total_amt - u_ad_limit);

                // bill_no; 提前施工申请单号;user_tqsgdh
                // u_ad_limit; 	提前施工金额;user_tqsg_amt
                // u_ad_total_amt - u_ad_limit;剩余金额;user_rest_sgamt
            }
        );
    });
    function getPtInfoByPhid() {
        if (mstform.getItem("PhidPc").getValue()) {
            execServer(
                "projectSjbm",
                { phid: `'${mstform.getItem("PhidPc").getValue()}'` },
                function (res) {
                    try {
                        const datas = JSON.parse(res.data)[0].extendObjects;
                        //商机号
                        mstform.getItem("user_sjh").setValue(datas.user_sjbm);
                        //商机编码
                        mstform.getItem("user_sjname").setValue(datas.user_sjmc);
                        BatchBindCombox([mstform.getItem("user_sjh")]);
                        BatchBindCombox([mstform.getItem("user_sjname")]);
                    } catch (error) { }
                }
            );
            execServer(
                "getPtInfoByPhid",
                { phid: mstform.getItem("PhidPc").getValue() },
                function (res) {
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    mstform.getItem("user_division").setValue(datas.org_phid); //事业部or组织
                    mstform
                        .getItem("user_regional_center")
                        .setValue(datas.regional_center_phid); //区域中心
                    mstform.getItem("user_pc_no").setValue(datas.pc_no); //项目编号
                    mstform
                        .getItem("user_project_manager")
                        .setValue(datas.project_manager_phid); //项目经理
                    mstform.getItem("user_fcur_type").setValue(1); //人民币
                    mstform.getItem("user_dept_bussine").setValue(datas.user_sqgw_phid); //部门商务
                    BatchBindCombox([mstform.getItem("user_division")]);
                    BatchBindCombox([mstform.getItem("user_regional_center")]);
                    BatchBindCombox([mstform.getItem("user_pc_no")]);
                    BatchBindCombox([mstform.getItem("user_project_manager")]);
                    BatchBindCombox([mstform.getItem("user_fcur_type")]);
                    BatchBindCombox([mstform.getItem("user_dept_bussine")]);
                }
            );
        }
    }
    // dgrid.addListener("edit", function (editor, e) {
    //     let record = e.record;
    //     console.log(record, "record");
    //     if (e.originalValue == e.value) {
    //         return;
    //     }
    // });

    dgrid
        .getColumn("ItemDataNo")
        .getEditor()
        .addListener("helpselected", async function (record) {
            let data = dgrid.getSelectionModel().getSelection();
            if (!record.data.PhidItemdata) return; //判断是否为空

            execServer(
                "getrestqtyview",
                { itemName: `'${record.data.PhidItemdata}'` },
                async function (res) {
                    if (res.data.length > 0) {
                        console.log(JSON.parse(res.data), "有数据");
                        let mergedData = mergeSimilarItems(JSON.parse(res.data));
                        if (mergedData[0].extendObjects.u_rest_qty) {
                            let data = dgrid.getSelectionModel().getSelection();
                            data[0].set(
                                "user_rest_wz",
                                mergedData[0].extendObjects.u_rest_qty
                            );
                            dgrid.getView().refresh();
                        }
                    } else {
                        console.log(res, "未查到数据");
                        dgrid.getView().refresh();
                    }
                    dgrid.getView().refresh();
                }
            );
        });

// //     // 表体单据引用触发;
let req_total = 0
let reqs = []
setInterval(()=>{
    console.log(`请求数量`,req_total);
},6000)
    dstore.on("datachanged", function (dstore, eOpts) {
        allRequest(dstore)
    });
    async function allRequest(dstore){
        if(djLock){
            clearTimeout(djLock)
        }
        djLock = setTimeout(async ()=>{
            dstore.each(async function (record) {
                if (!record.data.PhidItemData) return; //判断是否为空
                reqs.push(new Promise((resolve)=>{
                    setTimeout(()=>{
                        execServer(
                            "getDHZQItemDataInfo",
                            { phid: record.data.PhidItemData },
                            function (res) {
                                req_total+=1
                                try {
                                    const datas = JSON.parse(res.data);
                                    let DHZQ1 = datas[0].extendObjects.user_dhzq;
                                    record.set("user_delivery_cycle", DHZQ1);
                                    let DHZQ2 = datas[0].extendObjects.user_cgzq;
                                    const newDate2 = addDaysToDate(
                                        mstform.getItem("BillDt").value,
                                        DHZQ2
                                    );
                                    record.set("user_ckdh_dt", newDate2);
                                    if (DHZQ2 && DHZQ1) {
                                        const newDate1 = addDaysToDate(
                                            mstform.getItem("BillDt").value,
                                            Number(DHZQ1) + Number(DHZQ2)
                                        );
                                        record.set("user_exp_arrival_date", newDate1);
                                    }
                                    resolve("success")
                                } catch (error) {
                                }
                                // mstform
                                // 	.getItem("user_org_apply")
                                // 	.setValue(datas[0].extendObjects.oname);
                                dgrid.getView().refresh();
                            }
                        );
                    },0)
                }))
               
                
                console.log(record.data.PhidItemdata,'测试');
                if (record.data.PhidItemdata == '') {
                    console.log(`return `,record,record.data,record.data.PhidItemData,record.get("PhidItemData"));
                    return
                }; //判断是否为空
                // execServer(
                //     "getrestqtyview",
                //     { itemName: `'${record.data.PhidItemdata}'` },
                //     function (res) {
                //         console.log(`物资剩余`,JSON.parse(res.data));
                //         if (res.data.length > 0) {
                //             let mergedData = mergeSimilarItems(JSON.parse(res.data));
                            
                //             if (mergedData[0].extendObjects.u_rest_qty) {
                //                 let data = dgrid.getSelectionModel().getSelection();
                //                 data[0].set(
                //                     "user_rest_wz",
                //                     mergedData[0].extendObjects.u_rest_qty
                //                 );
                //                 dgrid.getView().refresh();
                //             }
                //         } else {
                            
                //             dgrid.getView().refresh();
                //         }
    
                //         dgrid.getView().refresh();
                //     }
                // );
            });
            const result = await Promise.all(reqs)
            console.log(`请求完成`,result);
        },1000)
        
    }
}
//到货周期时间计算

function addDaysToDate(dateStr, days) {
    // 将日期字符串转换为 Date 对象
    const date = new Date(dateStr);
    // 在当前日期的基础上加上指定的天数
    date.setDate(date.getDate() + parseInt(days));

    // 获取新日期的年、月、日
    const year = date.getFullYear();
    // 月份需要加 1，因为 getMonth 返回值是 0 - 11
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    // 按照 YYYY.MM.DD 格式返回新日期
    return `${year}-${month}-${day}`;
}

function mergeSimilarItems(arr) {
    let result = [];
    arr.forEach((item) => {
        let found = false;
        result.forEach((existing) => {
            let shouldMerge = true;
            for (let key in item.extendObjects) {
                if (
                    key !== "u_rest_qty" &&
                    key !== "pc" &&
                    item.extendObjects[key] !== existing.extendObjects[key]
                ) {
                    shouldMerge = false;
                    break;
                }
            }
            if (shouldMerge) {
                existing.extendObjects.u_rest_qty =
                    (existing.extendObjects.u_rest_qty || 0) +
                    (item.extendObjects.u_rest_qty || 0);
                found = true;
            }
        });
        if (!found) {
            result.push({
                dic: item.dic,
                extendObjects: {
                    ...item.extendObjects,
                },
            });
        }
    });
    return result;
}
function mergeSimilarItems2(arr) {
    let result = [];
    arr.forEach((item) => {
        let found = false;
        result.forEach((existing) => {
            let shouldMerge = true;
            for (let key in item.extendObjects) {
                if (
                    key !== "u_rest_qty" &&
                    item.extendObjects[key] !== existing.extendObjects[key]
                ) {
                    shouldMerge = false;
                    break;
                }
            }
            if (shouldMerge) {
                existing.extendObjects.u_rest_qty =
                    (existing.extendObjects.u_rest_qty || 0) +
                    (item.extendObjects.u_rest_qty || 0);
                found = true;
            }
        });
        if (!found) {
            result.push({
                dic: item.dic,
                extendObjects: {
                    ...item.extendObjects,
                },
            });
        }
    });
    return result;
}
function createTable(mergedData) {
    // 创建一个 style 元素
    const style = document.createElement("style");
    // 设置 style 元素的内容
    style.textContent = `
           .center-table {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    border-collapse: collapse;
                    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                    z-index: 100;
                }
           .center-table th,
           .center-table td {
                    padding: 10px;
                    border: 1px solid #ddd;
                    background-color: #fff;
                }
           .center-table th {
                    background-color: #f2f2f2;
                }
              .close-button {
                  position: absolute;
                    top: 0;
                    right: 0;
                    cursor: pointer;
                    background-color: #2c85b1;
                    color: white;
                    padding: 5px;
                    border: none;
                    border-radius: 50%;
                    width: 20px;
                    height: 20px;
                    line-height: 1;
                    opacity: 0.5;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    transition: opacity 0.3s;
                }
              .close-button:hover {
                    background-color: #d32f2f;
                }
            `;
    // 将 style 元素添加到 head 元素中
    document.head.appendChild(style);

    // 创建表格元素
    const table = document.createElement("table");
    table.className = "center-table";

    // 创建表头元素
    const thead = document.createElement("thead");
    const headerRow = document.createElement("tr");
    const headers = ["项目名称", "物料名称", "剩余数量"];
    headers.forEach((headerText) => {
        const th = document.createElement("th");
        th.textContent = headerText;
        headerRow.appendChild(th);
    });
    thead.appendChild(headerRow);
    table.appendChild(thead);

    // 创建表格内容（示例数据）
    const tbody = document.createElement("tbody");
    let newArray = [];
    mergedData.forEach((item, index) => {
        const { u_rest_qty = 0, pc = "", itemname = "" } = item.extendObjects;
        newArray.push([pc, itemname, u_rest_qty]);
    });
    newArray.forEach((rowData) => {
        const tr = document.createElement("tr");
        rowData.forEach((cellData) => {
            const td = document.createElement("td");
            td.textContent = cellData;
            tr.appendChild(td);
        });
        tbody.appendChild(tr);
    });
    table.appendChild(tbody);

    // 创建关闭按钮
    const closeButton = document.createElement("button");
    closeButton.textContent = "X";
    closeButton.className = "close-button";
    closeButton.addEventListener("click", () => {
        tableContainer.removeChild(table);
        // tableContainer.removeChild(closeButton);
    });

    // 将表格和关闭按钮添加到页面中的指定容器
    const tableContainer = document.getElementsByClassName("x-body")[0];
    tableContainer.appendChild(table);
    table.appendChild(closeButton);
}
